﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.Data;

public partial class Pages_Private_SubscribePackage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindPackageList();
        }
    }

    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Subscribe to Package");
    }

    protected void BindPackageList()
    {
        UtilityDAO dao = new UtilityDAO();
        DataSet ds = dao.GetDataSet(AppSQL.GET_ACTIVE_PACKAGE_LIST, null, false);
        rptPackageList.DataSource = ds.Tables[0];
        rptPackageList.DataBind();
    }
    protected void SaveSubscription()
    {
        int packageID = Request.Form["rdbPackage"].ToInt();
        if (packageID > 0)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            if (context.PackageSubscriptions.FirstOrDefault(P => P.CustomerID == SessionCache.CurrentUser.CustomerID && P.ExpireDate >= DateTime.Now) == null)
            {
                var package = context.Packages.FirstOrDefault(P => P.ID == packageID);
                PackageSubscription subscription = new PackageSubscription();
                subscription.CustomerID = SessionCache.CurrentUser.CustomerID;
                subscription.PackageID = package.ID;
                subscription.ProductCount = package.ProductLimit;
                subscription.StartDate = DateTime.Now;
                subscription.ExpireDate = DateTime.Now.AddDays(package.Duration);
                
                context.AddToPackageSubscriptions(subscription);
                context.SaveChanges();
                WebUtil.ShowMessageBox(divMessage, "You have successfully subscribed to the package.", false);
            }
            else
                WebUtil.ShowMessageBox(divMessage, "You already have an active subscription.", true);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveSubscription();
        }
    }
}